package com.tt.vtg.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.tt.vtg.dao.PermissionDao;
import com.tt.vtg.dao.entity.Permission;
import com.tt.vtg.dao.entity.Role;
import com.tt.vtg.dao.entity.User;
import com.tt.vtg.service.PermissionService;
import com.tt.vtg.service.UserService;

@Component("permissionSvc")
@Transactional(value = "txManager")
public class PermissionServicecImpl implements PermissionService {
	@Autowired
	private PermissionDao permissionDao;
	@Autowired
	private UserService userService;

	@Override
	@Transactional(value = "txManager", readOnly = true)
	public Permission get(Long id) {
		return permissionDao.findOne(id);
	}

	@Override
	public void save(Permission t) {
		throw new UnsupportedOperationException("Permission could not be operated.");
	}

	@Override
	public void update(Permission t) {
		throw new UnsupportedOperationException("Permission could not be operated.");
	}

	@Override
	public Permission getById(String id) {
		throw new UnsupportedOperationException("Permission could not be operated.");
	}

	@Override
	public void delete(long id) {
		throw new UnsupportedOperationException("Permission could not be operated.");
	}

	@Override
	public List<Permission> getAll() {
		return Collections.unmodifiableList(permissionDao.findAll());
	}

	@Override
	public List<Permission> loadUserPermission(Map<String, Object> map) {
//		List<Permission> plist = new ArrayList<>();
		User user = userService.findOne(Long.valueOf(map.get("userid").toString()));
		Set<Role>roles= user.getRoles();
		
		return roles.stream().flatMap(r->r.getPermissions().stream()).collect(Collectors.toList());
		
//		roles.forEach(r ->{
//			System.out.println(r.getPermissions().size());
//		} );
//		return plist;
	}

}
